const { PrismaClient } = require('@prisma/client');
const bcrypt = require('bcryptjs');
const fs = require('fs');
const path = require('path');
const { initPermissionsAndRoles } = require('./permission-seed');

const prisma = new PrismaClient();

async function initDatabase() {
  try {
    console.log('开始初始化数据库...');

    // 初始化权限和角色
    await initPermissionsAndRoles();
    console.log('权限和角色初始化完成');

    // 创建部门
    const departments = [
      { name: '管理部', description: '负责整体管理工作' },
      { name: '销售部', description: '负责销售和客户关系' },
      { name: '运营部', description: '负责日常运营' },
      { name: '财务部', description: '负责财务管理' },
      { name: '仓储部', description: '负责库存管理' }
    ];

    for (const dept of departments) {
      await prisma.department.upsert({
        where: { name: dept.name },
        update: { description: dept.description },
        create: {
          ...dept,
          updatedAt: new Date()
        }
      });
    }
    console.log('部门初始化完成');

    // 创建用户
    const hashedPassword = await bcrypt.hash('123456', 10);

    // 获取角色ID
    const adminRole = await prisma.role.findUnique({
      where: { name: 'admin' }
    });
    
    const staffRole = await prisma.role.findUnique({
      where: { name: 'staff' }
    });

    await prisma.user.upsert({
      where: { username: 'admin' },
      update: {
        password: hashedPassword,
        status: true,
        departmentId: 1,
        roleId: adminRole.id
      },
      create: {
        username: 'admin',
        password: hashedPassword,
        name: '管理员',
        roleId: adminRole.id,
        departmentId: 1,
        status: true,
        updatedAt: new Date()
      },
    });

    await prisma.user.upsert({
      where: { username: 'staff' },
      update: {
        password: hashedPassword,
        status: true,
        departmentId: 2,
        roleId: staffRole.id
      },
      create: {
        username: 'staff',
        password: hashedPassword,
        name: '收银员',
        roleId: staffRole.id,
        departmentId: 2,
        status: true,
        updatedAt: new Date()
      },
    });
    console.log('用户初始化完成');

    // 创建渠道
    const channels = [
      { name: '美团外卖', code: 'meituan', desc: '通过美团外卖平台配送', iconUrl: '/icons/meituan.svg' },
      { name: '饿了么', code: 'ele', desc: '通过饿了么平台配送', iconUrl: '/icons/eleme.svg' },
      { name: '抖音小店', code: 'douyin', desc: '通过抖音小店售卖', iconUrl: '/icons/douyin.svg' },
      { name: '京东', code: 'jd', desc: '通过京东平台售卖', iconUrl: '/icons/jd.svg' },
      { name: '小程序', code: 'miniapp', desc: '通过微信小程序售卖', iconUrl: '/icons/miniprogram.svg' },
      { name: '线下', code: 'offline', desc: '门店线下销售', iconUrl: '/icons/offline.svg' },
      { name: '线下店铺', code: 'store', desc: '线下实体店销售', iconUrl: '/icons/offline.svg' },
      { name: '抖音', code: 'dy', desc: '抖音电商', iconUrl: '/icons/douyin.svg' },
      { name: '其他', code: 'other', desc: '其他销售渠道', iconUrl: '/icons/offline.svg' }
    ];

    for (const channel of channels) {
      // 先检查是否存在同名渠道
      const existingChannel = await prisma.channel.findFirst({
        where: { name: channel.name }
      });

      if (existingChannel) {
        // 更新现有渠道，确保code字段正确
        await prisma.channel.update({
          where: { id: existingChannel.id },
          data: {
            code: channel.code, // 确保有正确的code
            desc: channel.desc,
            iconUrl: channel.iconUrl // 更新图标URL
          }
        });
        console.log(`更新渠道: ${channel.name}`);
      } else {
        // 创建新渠道
        await prisma.channel.create({
          data: {
            ...channel,
            updatedAt: new Date()
          }
        });
        console.log(`添加渠道: ${channel.name}`);
      }
    }
    console.log('渠道初始化完成');

    // 创建分类
    const categories = [
      { name: '国产啤酒', desc: '中国生产的各类啤酒' },
      { name: '进口啤酒', desc: '从国外进口的啤酒' },
      { name: '精酿啤酒', desc: '小批量精心酿造的特色啤酒' },
      { name: '果味啤酒', desc: '添加水果风味的啤酒' },
    ];

    for (const category of categories) {
      // 先检查是否存在同名分类
      const existingCategory = await prisma.category.findFirst({
        where: { name: category.name }
      });

      if (existingCategory) {
        // 更新现有分类
        await prisma.category.update({
          where: { id: existingCategory.id },
          data: {
            desc: category.desc
          }
        });
        console.log(`更新分类: ${category.name}`);
      } else {
        // 创建新分类
        await prisma.category.create({
          data: {
            ...category,
            updatedAt: new Date()
          }
        });
        console.log(`添加分类: ${category.name}`);
      }
    }
    console.log('分类初始化完成');

    // 创建支付方式
    const paymentMethods = [
      { id: 'cash', name: '现金支付', icon: 'money' },
      { id: 'wechat', name: '微信支付', icon: 'wechat' },
      { id: 'alipay', name: '支付宝支付', icon: 'alipay' },
      { id: 'complimentary', name: '招待', icon: 'gift' }
    ];

    for (const method of paymentMethods) {
      await prisma.paymentMethod.upsert({
        where: { id: method.id },
        update: {
          name: method.name,
          icon: method.icon,
          status: true
        },
        create: {
          id: method.id,
          name: method.name,
          icon: method.icon,
          status: true,
          updatedAt: new Date()
        }
      });
    }
    console.log('支付方式初始化完成');

    // 导入商品数据 - 仅在没有商品数据时执行
    try {
      const existingProductCount = await prisma.product.count();

      if (existingProductCount === 0) {
        console.log('数据库中没有商品数据，开始导入备份数据...');

        const productsDataPath = path.join(__dirname, 'products-data-backup.json');
        const productsData = JSON.parse(fs.readFileSync(productsDataPath, 'utf8'));

        console.log(`读取到${productsData.length}条商品数据`);

        let addedCount = 0;

        for (const product of productsData) {
          await prisma.product.create({
            data: {
              ...product,
              updatedAt: new Date()
            }
          });
          addedCount++;
          console.log(`添加商品: ${product.name}`);
        }

        console.log(`商品初始化完成! 添加: ${addedCount} 个商品`);
      } else {
        console.log(`数据库中已有 ${existingProductCount} 个商品，跳过商品数据导入以避免覆盖现有数据`);
      }
    } catch (error) {
      console.error('商品导入过程中出错:', error);
    }

    // 初始化仓库
    // 先检查是否存在默认仓库
    const existingWarehouse = await prisma.warehouse.findFirst({
      where: { name: '默认仓库' }
    });

    if (existingWarehouse) {
      await prisma.warehouse.update({
        where: { id: existingWarehouse.id },
        data: {
          location: '默认位置',
          status: true
        }
      });
      console.log('更新默认仓库');
    } else {
      await prisma.warehouse.create({
        data: {
          name: '默认仓库',
          location: '默认位置',
          status: true,
          updatedAt: new Date()
        }
      });
      console.log('创建默认仓库');
    }

    console.log('仓库初始化完成');

    // 初始化供应商
    const suppliers = [
      { name: '青岛啤酒供应商', contactPerson: '张经理', phone: '13800138001', address: '青岛市黄岛区' },
      { name: '百威啤酒供应商', contactPerson: '李经理', phone: '13800138002', address: '武汉市江夏区' },
      { name: '哈尔滨啤酒供应商', contactPerson: '王经理', phone: '13800138003', address: '哈尔滨市南岗区' }
    ];

    for (const supplier of suppliers) {
      // 先检查是否存在同名供应商
      const existingSupplier = await prisma.supplier.findFirst({
        where: { name: supplier.name }
      });

      if (existingSupplier) {
        await prisma.supplier.update({
          where: { id: existingSupplier.id },
          data: {
            contactPerson: supplier.contactPerson,
            phone: supplier.phone,
            address: supplier.address
          }
        });
        console.log(`更新供应商: ${supplier.name}`);
      } else {
        await prisma.supplier.create({
          data: {
            ...supplier,
            updatedAt: new Date()
          }
        });
        console.log(`添加供应商: ${supplier.name}`);
      }
    }
    console.log('供应商初始化完成');

    console.log('数据库初始化完成!');
  } catch (error) {
    console.error('数据库初始化失败:', error);
    process.exit(1);
  } finally {
    await prisma.$disconnect();
  }
}

// 如果此文件被直接执行，则运行initDatabase函数
if (require.main === module) {
  initDatabase();
}

// 导出initDatabase函数，以便其他文件可以导入
module.exports = { initDatabase }; 